package com.pig4cloud.pig.village.rules.generator.conditions;

import java.util.Arrays;
import java.util.List;

import com.pig4cloud.pig.village.rules.RuleCondition;

public class ArrayParser extends AbstractConditionParser {

	/**
	 * Parse array case
	 * Input: key is school, value is "foo,bar".
	 * Output: (school == "foo" || school == "bar")
	 * @param ruleCondition
	 * @return
	 */
	public StringBuilder parse(RuleCondition ruleCondition) {
		List<String> conditionValues;
		StringBuilder subConditionBuilder = new StringBuilder();
		if (ruleCondition.getConditionValue().contains(",")) {
			// Use "OR" for multiple condition values
			// To build ("key==foo || key==bar")
			StringBuilder orConditionBuilder = new StringBuilder("(");
			conditionValues = Arrays.asList(ruleCondition.getConditionValue().split("\\s*,\\s*"));
			conditionValues.forEach((v) -> {
				orConditionBuilder.append(ruleCondition.getConditionKey())
						.append(EQUALS_OPERATOR)
						.append("\"").append(v).append("\"")
						.append(OR_OPERATOR);
			});
			orConditionBuilder.delete(orConditionBuilder.length() - OR_OPERATOR.length(), orConditionBuilder.length());
			orConditionBuilder.append(")");
			subConditionBuilder.append(orConditionBuilder);
		}
		return subConditionBuilder;
	}
}
